<?php

/**
 * 淘宝退款API
 *
 * Class RefundsAPI
 */
class RefundsAPI {
    private $_client;

    /**
     * Constructor
     *
     * @param $options
     *
     * @throws APIException
     */
    public function __construct($options) {
        $client = isset($options[0]) ? $options[0] : null;
        if (!$client || !$client instanceof TaobaoClient) {
            throw new APIException(10001, '淘宝API 客户端载入失败');
        }
        $this->_client = $client;
    }


    /**
     * 获取单笔退款信息
     *
     * @param $refund_id
     *
     * @return mixed
     */
    public function get($refund_id) {
        $paras = array(
            'fields' => 'refund_id, tid, buyer_nick, seller_nick, total_fee, status,
                created, refund_fee, oid, good_status, company_name, sid, payment, reason, desc,
                has_good_return, modified, order_status',
            'refund_id' => $refund_id
        );
        $jsonData=$this->_client->api('taobao.refund.get', $paras);
        if(isset($jsonData['error_response'])){
            return array();
        }
        $result=isset($jsonData['refund_get_response']['refund'])?$jsonData['refund_get_response']['refund']:array();
        return $result;
    }

    /**
     * 获取退款列表
     *
     * @param $page
     * @param $page_size
     * @param $options
     *
     * @return mixed
     */
    public function getList($page = 1, $page_size, $options=array()) {
        $use_has_next=isset($options['use_has_next'])?$options['use_has_next']:'false';
        $paras = array(
            'fields' => 'refund_id, tid, buyer_nick, seller_nick, total_fee, status,
                created, refund_fee, oid, good_status, company_name, sid, payment, reason, desc,
                has_good_return, modified, order_status',
            'page_no' => $page,
            'page_size' => $page_size,
            'use_has_next' => $use_has_next
        );
        if (isset($options['buyer_nick'])&&$options['buyer_nick']) {
            $paras['buyer_nick'] = $options['buyer_nick'];
        }
        if (isset($options['start_modified']) && $options['start_modified']) {
            $paras['start_modified'] = $options['start_modified'];
        }
        if (isset($options['end_modified']) && $options['end_modified']) {
            $paras['end_modified'] = $options['end_modified'];
        }
        if(isset($options['status']) && $options['status']){
            $paras['status']=$options['status'];
        }
        $jsonData=$this->_client->api('taobao.refunds.receive.get', $paras);
        $construct = $this->_parseStructure('refunds', explode(',', $paras['fields']));
        $result = $this->_parseGetResponse($jsonData, 'refunds_receive_get', $construct);
        return $result;
    }


    /**
     * 处理淘宝交易数据
     *
     * @param $jsonData
     * @param $response_name
     * @param $construct
     *
     * @return array
     * @throws APIException
     */
    private function _parseGetResponse($jsonData, $response_name, $construct = array()) {
        if (isset($jsonData['error_response'])) {
            $errorResponse = $jsonData['error_response'];
            $msg = isset($errorResponse['sub_msg']) ? $errorResponse['sub_msg'] : $errorResponse['msg'];
            throw new APIException(10000, $msg, $errorResponse);
        }
        $response_name.='_response';
        $jsonData = isset($jsonData[$response_name]) ? $jsonData[$response_name] : $jsonData;
        $refunds = isset($jsonData['refunds']) ? $jsonData['refunds'] : $jsonData;
        unset($jsonData['refunds']);
        $structure = isset($construct['refund']) ? $construct['refund'] : array();
        $refund=isset($refunds['refund'])?$refunds['refund']:array();
        $data=array_merge($structure, $refund);
        $result=array();
        if (isset($jsonData['total_results'])||isset($jsonData['has_next'])) {
            $structure = isset($construct['refunds']) ? $construct['refunds'] : array();
            foreach ($data as &$refund) {
                if (!$refund) {
                    continue;
                }
                $refund = array_merge($structure, $refund);
            }
            $result = array(
                'total_records' => isset($jsonData['total_results'])?$jsonData['total_results']:null,
                'data' => array('refunds' => $data)
            );
        }
        if(isset($jsonData['has_next'])&&$jsonData['has_next']){
            $result['has_next']=$jsonData['has_next'];
        }
        return $result;
    }

    /**
     * 处理淘宝响应的结构
     *
     * @param string $name
     * @param $fields
     *
     * @return array
     */
    private function _parseStructure($name = '', $fields) {
        $structures = array();
        if (!$name || !$fields) {
            return $structures;
        }
        $structures[$name] = array();
        foreach ($fields as $field) {
            $field = preg_replace('/\s+/', '', $field);
            if (strpos($field, '.') !== false) {
                $a = explode('.', $field);
                $structures[$a[0]][$a[1]] = '';
            } else {
                $structures[$name][$field] = '';
            }
        }
        return $structures;
    }
}